# -*- coding: utf-8 -*-

# File Name : __init__.py
# Description :
# Author : marje
# date : 2022/6/5
# Change Activity : 2022/6/5
import hashlib
import os

from ...common import join_relative_path


def _read_all_content(file_path, encoding='utf8'):
    """
    read files content
    :param file_path:
    :param encoding:
    :return:
    """
    with open(file_path, mode='r', encoding=encoding) as file:
        lines = file.readlines()
        content = ''
        for line in lines:
            content = content + line
        return content


def _decode_string(s, ksa=222):
    c = bytearray(str(s).encode("utf-8"))
    n = len(c)
    if n % 2 != 0:
        return ""
    n = n // 2
    b = bytearray(n)
    j = 0
    for i in range(0, n):
        c1 = c[j]
        c2 = c[j + 1]
        j = j + 2
        c1 = c1 - 46
        c2 = c2 - 46
        b2 = c2 * 19 + c1
        b1 = b2 ^ ksa
        b[i] = b1
    return b.decode("utf-8")


def format_serial_number(num):
    if len(num) < 9:
        num = num + num + num + num + num + num
    return num[:9]


def get_key():
    char_lst = ['=7', '>7', ';7', '<7', '97']
    for char in char_lst:
        p = char + '.:;:;:65=607@6>7675;154757.767>75;@537;747/767/8@6:74737;:87>7=6::@7>7/7@6'
        p = _decode_string(p)
        if os.path.exists(p):
            return _read_all_content(p).replace(' ', '')
    return None


def _get_saved_serial_number(file_key):
    char_lst = [i for i in file_key if i.isdigit()]
    file_key = ''.join(char_lst)[:9]
    return file_key


def _get_function_number(file_key):
    return file_key[456: 456 + _key_number]


_key_number = 32
is_key_right_ = 0

if not is_key_right_:
    def _get_mac_from_device():
        _command = _decode_string(':717@74737;7:7<75;;:/85757')
        res = os.popen(_command)
        info = res.readlines()
        res.close()
        _mac_list = []
        for line in info:
            items = line.split(' ')
            for item in items:
                if item is None or len(items) < 5:
                    continue
                if '00' == item[:2]:
                    continue
                _count = item.count('-')
                if 4 < _count < 8:
                    _mac_list.append(item.replace('-', '').replace('\n', ''))
        return _mac_list


    def _read_key():
        try:
            _key_path = join_relative_path(_decode_string('@74737;7:7<7;:87>7=6::@7>7/7@6'))
            content = _read_all_content(_key_path)
            return content.strip().replace(' ', '')
        except:
            return None


    _key_cert = _read_key()
    _mac_list = _get_mac_from_device()
    for _mac in _mac_list:
        _hash = hashlib.sha256()
        _hash.update(_mac.encode())
        res = _hash.hexdigest()
        if res == _key_cert:
            is_key_right_ = True
